--
-- Author: ping.wang
-- Date: 2018-07-11 14:02:34
--
-- AuctionNormalBuyFixedRender
--

local ClassRef = app.mvc.createRenderClass(...)
local string_format = string.format

--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.AuctionBuy1Render))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self:setContentSize( self._ui.Panel:getContentSize() )
    self._seperatePrice = self._ui.Panel_num:findChild("num") --单价
    self._totalPriceText = self._ui.Panel_num_total:findChild("num") --总价格
    self._myGoldNum = self._ui.Panel_num_my:findChild("num") --我所拥有的金币数
    self._curNumText = self._ui.Panel_supplies:findChild("num") --中央显示的当前数量 内容为"数量10/99"
    self._ui.Panel_supplies:addClickEventListener(function() executeFunc(self._onClick, "showMiniKeyboard") end)
    local minusBtn = self._ui.Panel_supplies:findChild("Button_minus")
    minusBtn:addTouchEventListener(handler( self, self._minusBtnClickEvent ) )
    local plusBtn = self._ui.Panel_supplies:findChild("Button_plus")
    plusBtn:addTouchEventListener(handler( self, self._plusBtnClickEvent ) )

    ----------小键盘start--------------
    local suppliesPanelBg = self._ui.Panel_supplies:findChild("bg")

    display.uiAddClick( suppliesPanelBg, function()
        local btn = self._ui.Panel_supplies:findChild("Button_plus")
        local posTemp = btn:convertToWorldSpace(cc.p(0,0))
        local width, height = btn:getContentSize2()
        posTemp.x = posTemp.x + width

        executeFunc(self._onClick, "showMiniKeyboard", {posTemp,self._curNum,handler( self, self.setAndGetBuyNum )} )
    end )
    ----------小键盘end----------------

    self._ui.btn_buy:addClickEventListener(handler( self, self._buyBtnClickEvent ))
    self._curNum = 1 --当前显示的数量
    self._myGoldIcon = self._ui.Panel_num_my:findChild("gold")
    self._maxCount = 0
    self._curNumText:setVisible(false)
    self._totalPriceText:setVisible(false)

    --普通商品的购买 icon
    local goldIcon1 = self._ui.Panel_num:findChild("gold")
    local goldIcon2 = self._ui.Panel_num_total:findChild("gold")
    local goldIcon3 = self._ui.Panel_num_my:findChild("gold")

    self._coinId = tonumber(GD:getSystemPar( "auctionNormalGoodsLootType",99))
    self._coinConfig = GD:getCoinConfig(self._coinId)
    local iconPath = string.format("%s%s.png",Res.coinIconPath,self._coinConfig.bigicon)
    goldIcon1:loadTexture(iconPath)
    goldIcon2:loadTexture(iconPath)
    goldIcon3:loadTexture(iconPath)

    self:refresh()
end

function ClassRef:refresh()
    if self._data then
        self:setVisible( true )
        local goodData = self._data.goodData
        self._myGoldNum:setString(string_format(L("auction_goldNum"),L(self._coinConfig.name),UD:getDaibiValue(self._coinId)))
        self:_adjustIconPosX(self._myGoldIcon,self._myGoldNum)
        self._seperatePrice:setString(string_format(L("auction_singlePrice"),goodData:getSellPrice()))
        self:_adjustIconPosX(self._ui.Panel_num:findChild("gold"),self._seperatePrice,self._ui["Panel/Panel_num/dot"])
        self:setAndGetBuyNum(1)
    else
        self:setVisible( false )
    end
end

--基于文本调整ICON的位置
function ClassRef:_adjustIconPosX(icon,text,dot)
    local parentPanelW = text:getPositionX()
    local fixedGoldenPosX = parentPanelW + text:getContentSize().width/2 + icon:getContentSize().width * 0.6
    icon:setPositionX(fixedGoldenPosX)
    if dot then
        local tempW = dot:getParent():getContentSize().width
        local length = text:getContentSize().width + icon:getContentSize().width
        if length >= tempW * 0.8 then
            local h = dot:getContentSize().height
            dot:setContentSize(tempW + length - tempW * 0.8,h)
        end
    end
end


--调整有文字的价格以及描述金币的位置
function ClassRef:_adjustIconPosAndDes(text,priceText,icon)
    local textWidth = text:getContentSize().width
    local priceWidth = priceText:getContentSize().width
    local parentWidth = text:getParent():getContentSize().width
    local startPosX = (parentWidth - priceWidth)/2
    text:setPositionX(startPosX)
    priceText:setPositionX(parentWidth/2 + textWidth/2)
    icon:setPositionX((parentWidth+ textWidth + priceWidth)/2 + icon:getContentSize().width * 0.6)
end

function ClassRef:setAndGetBuyNum(num)
    --local goodData = self._data.goodData
    if not self._soldListData then return 0 end

    local maxCount = self._maxCount
    if num > maxCount then
        num = maxCount
    elseif num < 1 then
        num = 1
    end

    self._curNum = num
    --todo 此价格也会更新 所以传进来的部分应该有右侧所有出售列表
    --及时计算总价 和 数量上限
    self._totalPrice = self:getBuyTotalPrice(num)
    --刷新显示 计算总价
    self._curNumText:setVisible(true)
    self._totalPriceText:setVisible(true)
    self._curNumText:setString(string_format(L("auction_tradeNum"),self._curNum,maxCount))
    self._totalPriceText:setString(self._totalPrice)

    --如果总价比身上的钱要多 则为红色 否则为绿色
    if UD:getGold() >= self._totalPrice then
        self._totalPriceText:setTextColor(cc.c3b(186,255,0))
    else
        self._totalPriceText:setTextColor(cc.c3b(255,105,85))
    end

    --均价需要刷新
    if num > 0 then
        self._seperatePrice:setString(string_format(L("auction_singlePrice"),math.ceil(self._totalPrice/num)))
    end
    self:_adjustIconPosAndDes(self._ui["Panel/Panel_num_total/tlt"],self._totalPriceText,self._ui["Panel/Panel_num_total/gold"])
    --同时要通知去刷新左侧面板
    executeFunc(self._onClick, "updateNormalBuyNum", self._curNum )
    return self._curNum
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end

--减少数量
function ClassRef:_minusBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:setAndGetBuyNum(self._curNum - 1) end)
end

--增大数量
function ClassRef:_plusBtnClickEvent(sender,eventType)
    self:_doLongPressClickEvent(sender,eventType,function() self:setAndGetBuyNum(self._curNum + 1) end)
end

function ClassRef:_doLongPressClickEvent(sender,eventType,callFunc)
    if eventType == ccui.TouchEventType.began then
        self._delayPressAction = self:performWithDelay(
            function()
                if not self._longPressAction then
                    self._longPressAction = self:schedule(callFunc,0.05)
                end
            end,0.3) --0.3秒后执行回调

    elseif eventType == ccui.TouchEventType.ended or eventType == ccui.TouchEventType.canceled then

        if self._delayPressAction then
            self:stopAction(self._delayPressAction)
            self._delayPressAction = nil
        end

        if self._longPressAction then
            self:stopAction(self._longPressAction)
            self._longPressAction = nil
        else
            callFunc()
        end
    end
end

--购买按钮按下去的时候触发事件
function ClassRef:_buyBtnClickEvent()
    --组合一下要传递的数据 钱不够需要提示或者按钮无效 TODO测试数据 需要ID 和 数量
    --local goodData = self._data.goodData
    local money = UD:getDaibiValue(self._coinId)
    if money < self._totalPrice then
        local coinConfig = GD:getCoinConfig(self._coinId)
        display.pushToast(string.format(L("auction_tips9"),L(coinConfig.name)))
    else
        --此处要传的数据{{uuid,count,price},{uuid,count,price}}
        if self._soldListData then
            executeFunc(self._onClick, "startBuyFixed",{self:getSendBuyData(self._curNum),self._curNum})
        end
    end
end

--界面左侧可以购买的商品列表信息
function ClassRef:setSoldListData(soldListData)
    self._soldListData = soldListData
    self._maxCount = 0
    for i = 1, #self._soldListData do
        self._maxCount = self._maxCount + self._soldListData[i]:getCount()
    end
    self:setAndGetBuyNum(1)
end

--根据当前设置的购买数量来得到实际购买数量和价格
function ClassRef:getBuyTotalPrice(buyTotalNum)
    local needBuyNum = buyTotalNum
    local tempNum = 0
    local goods
    local totalPrice = 0

    for i = 1, #self._soldListData do
        goods = self._soldListData[i]
        tempNum = goods:getCount()
        if needBuyNum > 0 then
            if needBuyNum >= tempNum then
                totalPrice = totalPrice + tempNum * goods:getSellPrice()
                needBuyNum = needBuyNum - tempNum
            else
                totalPrice = totalPrice + needBuyNum * goods:getSellPrice()
                needBuyNum = 0
            end
        end
    end

    return totalPrice
end

function ClassRef:getSendBuyData(buyTotalNum)
    local needBuyNum = buyTotalNum
    local tempNum = 0
    local goods
    --local totalPrice = 0

    local sendBuyData = {}
    for i = 1, #self._soldListData do
        goods = self._soldListData[i]
        tempNum = goods:getCount()
        if needBuyNum > 0 then
            if needBuyNum >= tempNum then
                table.insert(sendBuyData,{uuid = goods:getProductUUId(),count = tempNum,price = goods:getSellPrice()})
                --totalPrice = totalPrice + tempNum * goods:getSellPrice()
                needBuyNum = needBuyNum - tempNum
            else
                table.insert(sendBuyData,{uuid = goods:getProductUUId(),count = needBuyNum,price = goods:getSellPrice()})
                --totalPrice = totalPrice + needBuyNum * goods:getSellPrice()
                needBuyNum = 0
            end
        end
    end

    return sendBuyData
end

return ClassRef
